package com.nuoniu.sibanyun.service.work.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.common.result.HttpResult;
import com.nuoniu.sibanyun.entity.work.WorkReportForm;
import com.nuoniu.sibanyun.entity.work.WorkReportUser;
import com.nuoniu.sibanyun.mapper.work.WorkReportFormMapper;
import com.nuoniu.sibanyun.service.ISysOfficeService;
import com.nuoniu.sibanyun.service.work.IWorkReportFormService;
import com.nuoniu.sibanyun.service.work.IWorkReportUserService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;

/**
 * <p>
 * 工作报表 服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2020-08-14
 */
@Service
public class WorkReportFormServiceImpl extends ServiceImpl<WorkReportFormMapper, WorkReportForm> implements IWorkReportFormService {

    @Autowired
    private IWorkReportUserService reportUserService;

    @Override
    public Page<WorkReportForm> pageList(Page pages, WorkReportForm reportForm) {
        UserInfo userInfo = UserThreadLocal.get();
        if (reportForm.getTabKey() == 1) {
            reportForm.setCreateUserId(userInfo.getUserId());
        } else if (reportForm.getTabKey() == 2) {
            reportForm.setSubmitId(userInfo.getUserId());
        } else {
            reportForm.setCcId(userInfo.getUserId().toString());
        }

        reportForm.setCompanyId(userInfo.getCompanyId());
        return baseMapper.pageList(pages, reportForm);
    }

    @Override
    public void returnReportForm(WorkReportForm reportForm) {
        baseMapper.returnReportForm(reportForm);
    }

    @Override
    public void submitReportForm(WorkReportForm reportForm) throws ParseException {
        UserInfo userInfo = UserThreadLocal.get();
        if(StringUtils.isNotBlank(reportForm.getCcId())) {
            String[] ids = reportForm.getCcId().split(",");
            for(String id : ids) {
                if(reportForm.getSubmitId().equals(id)) {
                    throw new NuoNiuException("报送人和抄送不能相同");
                }
            }
        }

        if(reportForm.getSubmitId().equals(userInfo.getUserId())) {
            throw new NuoNiuException("不能报送给自己");
        }

        WorkReportUser reportUser = reportUserService.getDetail(userInfo.getOfficeId(), reportForm.getType(), 1);
        WorkReportForm form = this.getById(reportForm.getId());
        reportForm.setCreateDate(form.getCreateDate());
        if(reportUser != null && StringUtils.isNotBlank(reportUser.getDeadline())) {
            Boolean flag = this.checkReport(reportForm, reportUser);
            if(!flag) {
                throw new NuoNiuException("提交失败,已超时");
            }
        }

        reportForm.setStatus(1);
        reportForm.setSubmitDate(LocalDateTime.now());
        this.updateById(reportForm);
    }

    @Override
    public void saveReportForm(WorkReportForm reportForm) throws ParseException {
        UserInfo userInfo = UserThreadLocal.get();
        WorkReportUser reportUser = reportUserService.getDetail(userInfo.getOfficeId(), reportForm.getType(), 1);
        if(reportForm.getId() != null) {
            WorkReportForm form = this.getById(reportForm.getId());
            if(form.getStatus() != 0) {
                throw new NuoNiuException("已提交,无法修改");
            }

            if(reportForm.getStatus() ==1 && form.getStatus() == 0) {
                if(reportUser != null && StringUtils.isNotBlank(reportUser.getDeadline())) {
                    reportForm.setCreateDate(form.getCreateDate());
                    Boolean flag = checkReport(reportForm, reportUser);
                    if(!flag) {
                        throw new NuoNiuException("提交失败,已超时");
                    }
                }
                reportForm.setSubmitDate(LocalDateTime.now());
            }
            //reportForm.setStatus(0);
            this.updateById(reportForm);
        }else {
            if(reportForm.getStatus() == 1 && reportUser != null && StringUtils.isNotBlank(reportUser.getDeadline())) {
                Boolean flag = checkReport(reportForm, reportUser);
                if(!flag) {
                    throw new NuoNiuException("提交失败,已超时");
                }
            }

            if(reportForm.getStatus() != 0) {
                reportForm.setSubmitDate(LocalDateTime.now());
            }

            reportForm.setOfficeId(userInfo.getOfficeId());
            reportForm.setOfficeName(userInfo.getOfficeName());
            reportForm.setCreateUserId(userInfo.getUserId());
            reportForm.setCreateUserName(userInfo.getRealName());
            reportForm.setCompanyId(userInfo.getCompanyId());
            this.save(reportForm);
        }
    }

    public Boolean checkReport(WorkReportForm reportForm, WorkReportUser reportUser) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        Integer month = calendar.get(Calendar.MONTH) + 1;
        Integer day = calendar.get(Calendar.DATE);
        String[] time = reportUser.getDeadline().split(",");
        if(time.length < 3) {
            return true;
        }
        if(reportForm.getType() == 1) { //日报
            if(time[0].equals("1")) { //当日
                Date d  = sdf.parse(year + "-" + month + "-" + day + " " + time[1] + ":" + time[2]);
                if(reportForm.getCreateDate().getTime() > d.getTime()) {
                    if(reportUser.getIsOvertime() == 0) {
                        return false;
                    }else {
                        reportForm.setStatus(2);
                    }
                }
            }else { //次日
                Date d  = sdf.parse(year + "-" + month + "-" + (day + 1) + " " + time[1] + ":" + time[2]);
                if(d.getTime() < reportForm.getCreateDate().getTime()) {
                    if(reportUser.getIsOvertime() == 0) {
                        return false;
                    }else {
                        reportForm.setStatus(2);
                    }
                }
            }
        }
        if(reportForm.getType() == 2) { //周报
            calendar.setTime(reportForm.getCreateDate());
            // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
            calendar.setFirstDayOfWeek(Calendar.MONDAY);
            // 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
            int dayWeek = calendar.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
            if (1 == dayWeek) {
                calendar.add(Calendar.DAY_OF_MONTH, -1);
            }
            // 获得当前日期是一个星期的第几天
            int week = calendar.get(Calendar.DAY_OF_WEEK);
            if(time[0].equals("1")) { //当周
                Date d  = sdf.parse(year + "-" + month + "-" + (day + (Integer.parseInt(time[1]) - week)) + " " + time[2] + ":" + time[3]);
                if(reportForm.getCreateDate().getTime() > d.getTime()) {
                    if(reportUser.getIsOvertime() == 0) {
                        return false;
                    }else {
                        reportForm.setStatus(2);
                    }
                }
            }else { //次周
                Date d  = sdf.parse(year + "-" + month + "-" + (day + (Integer.parseInt(time[1]) - week) + 7) + " " + time[2] + ":" + time[3]);
                if(d.getTime() < reportForm.getCreateDate().getTime()) {
                    if(reportUser.getIsOvertime() == 0) {
                        return false;
                    }else {
                        reportForm.setStatus(2);
                    }
                }
            }
        }
        if(reportForm.getType() == 3) { //月报
            if(time[0].equals("1")) { //当月
                Date d  = sdf.parse(year + "-" + month + "-" + time[1] + " " + time[2] + ":" + time[3]);
                if(d.getTime() < reportForm.getCreateDate().getTime()) {
                    if(reportUser.getIsOvertime() == 0) {
                        return false;
                    }else {
                        reportForm.setStatus(2);
                    }
                }
            }else {//次月
                Date d  = sdf.parse(year + "-" + (month + 1) + "-" + time[1] + " " + time[2] + ":" + time[3]);
                if(reportForm.getCreateDate().getTime() > d.getTime()) {
                    if(reportUser.getIsOvertime() == 0) {
                        return false;
                    }else {
                        reportForm.setStatus(2);
                    }
                }
            }
        }
        return true;
    }
}
